package com.pet.server.ext.action.message;

import java.util.Date;

import net.sf.json.JSONObject;

import com.pet.server.ext.ActionBase;
import com.pet.server.ext.ApiError;
import com.pet.server.ext.BeanToJson;
import com.pet.server.ext.Result;
import com.pet.server.ext.constants.BaseAttribute;
import com.pet.server.ext.data.AnswerInfo;
import com.pet.server.ext.data.UserInfo;
import com.pet.server.ext.service.RequestService;
import com.pet.server.ext.service.UserService;
import com.pet.server.ext.util.NumberUtil;
import com.pet.server.ext.util.Parameters;
import com.pet.server.ext.util.StringUtil;

public class Answer extends ActionBase{
	private AnswerInfo answer;
	public Answer(){
		needCheckAuth =true;
	}
	@Override
	public void initParameters(Parameters params) throws ApiError {
		answer = new AnswerInfo();
		answer.oid=NumberUtil.getInteger(params.getFieldValue("id"));
		answer.answer_type=params.getFieldValue("answer_type");
		answer.answer_text=params.getFieldValue("answer_text");
		answer.sessionid=params.getFieldValue("sessionid");
		answer.reply_id=NumberUtil.getInteger(params.getFieldValue("reply_id"), -1);	
		answer.create_time=new Date();
		if(StringUtil.isEmpty(answer.oid,answer.answer_type,answer.answer_text)){
			throw ApiError.Type.INVALID_PARAM.toException();
		}
	}
	@Override
	public Result invokeService() throws ApiError {
		UserService userService = new UserService();
		UserInfo u = userService.findUserInfoById(user.user_id);
		if(null==u){
			throw ApiError.Type.LOGIC_ERROR.toException();
		}
		RequestService requestService = new RequestService();
		answer.user_id=user.user_id;
		if(StringUtil.isEmpty(answer.sessionid)&&BaseAttribute.answer_type.request.toString().equals(answer.answer_type)){
			answer.sessionid=StringUtil.createSessionid(user.user_id, answer.oid);
		}
		if(BaseAttribute.answer_type.request.equals(answer.answer_type)&&requestService.isSession(answer.sessionid)){
			answer.answer_type=BaseAttribute.answer_type.session.toString();
		}
		userService.saveAnswerInfo(answer);
		answer.nick_name=u.nick_name;
		answer.ico_path=u.ico_path;
		
		JSONObject o =  BeanToJson.beanToJson(answer,"answer_type","oid","state");
		if(answer.reply_id>0){
			o.put("reply", userService.findAnswerInfo(answer.reply_id));
		}
		Result result = new Result();
		result.put("data", o);
	    return result;
	}
}
